﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Text;
using System.Security.Cryptography;
using System.Web;
using System.Net;

namespace Tools
{
    /// <summary>
    /// 字符串辅助类
    /// </summary>
    public class StringUtil
    {
        private static Regex regexBr = new Regex(@"(\r\n)", RegexOptions.IgnoreCase);
        //private static Dictionary<string, Regex> cachedRegexDictionary = new Dictionary<string, Regex>();
        private static Random rand = new Random();
        const string DEFAULT_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

        /// <summary>
        /// 
        /// </summary>
        public readonly static string[] SqlBlackKeyList = {"--",";--",";","/*","*/","@@","@",
                                           "char","nchar","varchar","nvarchar",
                                           "alter","begin","cast","create","cursor","declare","delete","drop","end","exec","execute",
                                           "fetch","insert","kill","open",
                                           "select", "sys","sysobjects","syscolumns",
                                           "table","update"};

        /// <summary>
        /// 2011-06-30 by 杜有发，签名内容
        /// </summary>
        /// <param name="rawContent"></param>
        /// <param name="salt"></param>
        /// <returns></returns>
        public static string SignContent(string rawContent, string salt)
        {
            string md5 = MD5(rawContent + salt);

            return string.Format("{0}{1}", rawContent, md5);
        }

        /// <summary>
        /// 验证签名，并得到原始内容 2011-06-30
        /// </summary>
        /// <param name="signedContent"></param>
        /// <param name="salt"></param>
        /// <param name="rawContent"></param>
        /// <returns></returns>
        public static bool ValidateSignedContent(string signedContent, string salt, out string rawContent)
        {
            rawContent = string.Empty;

            if (string.IsNullOrEmpty(signedContent))
                return false;

            int len = signedContent.Length;
            if (len <= 32)
                return false;

            string md5 = signedContent.Substring(len - 32);//最后32位
            rawContent = signedContent.Substring(0, len - 32);//原始内容

            if (md5 == MD5(rawContent + salt))
                return true;

            return false;
        }

        /// <summary>
        /// ResolveUrl 2011-01-17 增加，来自：http://www.codeproject.com/KB/aspnet/resolveurl.aspx
        /// </summary>
        /// <param name="relativeUrl"></param>
        /// <returns></returns>
        public static string ResolveUrl(string relativeUrl)
        {
            if (relativeUrl == null) throw new ArgumentNullException("relativeUrl");

            if (relativeUrl.Length == 0 || relativeUrl[0] == '/' || relativeUrl[0] == '\\')
                return relativeUrl;

            int idxOfScheme = relativeUrl.IndexOf(@"://", StringComparison.Ordinal);
            if (idxOfScheme != -1)
            {
                int idxOfQM = relativeUrl.IndexOf('?');
                if (idxOfQM == -1 || idxOfQM > idxOfScheme) return relativeUrl;
            }

            StringBuilder sbUrl = new StringBuilder();
            sbUrl.Append(HttpRuntime.AppDomainAppVirtualPath);
            if (sbUrl.Length == 0 || sbUrl[sbUrl.Length - 1] != '/') sbUrl.Append('/');

            // found question mark already? query string, do not touch!
            bool foundQM = false;
            bool foundSlash; // the latest char was a slash?
            if (relativeUrl.Length > 1
                && relativeUrl[0] == '~'
                && (relativeUrl[1] == '/' || relativeUrl[1] == '\\'))
            {
                relativeUrl = relativeUrl.Substring(2);
                foundSlash = true;
            }
            else foundSlash = false;
            foreach (char c in relativeUrl)
            {
                if (!foundQM)
                {
                    if (c == '?') foundQM = true;
                    else
                    {
                        if (c == '/' || c == '\\')
                        {
                            if (foundSlash) continue;
                            else
                            {
                                sbUrl.Append('/');
                                foundSlash = true;
                                continue;
                            }
                        }
                        else if (foundSlash) foundSlash = false;
                    }
                }
                sbUrl.Append(c);
            }

            return sbUrl.ToString();
        }

        /// <summary>
        /// MD5函数,用UTF8编码
        /// </summary>
        /// <param name="str">原始字符串</param>
        /// <returns>MD5结果</returns>
        public static string MD5(string str)
        {
            return MD5(str,Encoding.UTF8);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="str"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string MD5(string str, Encoding encoding)
        {
            MD5 md5 = MD5CryptoServiceProvider.Create();
            byte[] dataMd5 = md5.ComputeHash(encoding.GetBytes(str));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < dataMd5.Length; i++)
                sb.AppendFormat("{0:x2}", dataMd5[i]);
            return sb.ToString();
        }

        /// <summary>
        /// 得到本机IP，并不是web请求的客户端的IP，此方法用于winform里 2010-07-27增加
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIP()
        {
            string strHostName = Dns.GetHostName(); //得到本机的主机名
            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName); //取得本机IP
            string strAddr = ipEntry.AddressList[0].ToString();
            return (strAddr);
        }

        /// <summary>
        /// 得到类似"name=omeweb,age=25"里配置的值
        /// </summary>
        /// <param name="source"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetFeature(string source, string name)
        {
            return GetFeature(source, name, ",");
        }

        /// <summary>
        /// 得到类似"name=omeweb,age=25"里配置的值,其中分隔符可以指定，如果找不到，则返回空（非null）
        /// </summary>
        /// <param name="source"></param>
        /// <param name="name"></param>
        /// <param name="separator"></param>
        /// <returns></returns>
        public static string GetFeature(string source, string name, string separator)
        {
            if (string.IsNullOrEmpty(source))
                return "";

            //to do 有性能改善的空间,可以把exp缓存起来
            Regex exp;
            //string key = string.Format("GetFeature_{0}_{1}", name, separator);//2010-03-15 改进key
            //if (cachedRegexDictionary.ContainsKey(key))
            //{
            //    exp = cachedRegexDictionary[key];
            //}
            //else
            //{
                exp = new Regex("(^|" + separator + "|\\s)" + name + "\\s*=\\s*([^" + separator + "]*)(\\s|" + separator + "|$)", RegexOptions.IgnoreCase);
                //cachedRegexDictionary.Add(key, exp);
            //}
            Match mt = exp.Match(source);
            if (mt.Success)
                return mt.Groups[2].ToString();
            return "";
        }

        /*/// <summary>
        /// 更新类似"name=omeweb,age=25"里配置的key的值
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string UpdateFeature(string str, string key, string value)
        {
            if (string.IsNullOrEmpty(key))//key is null
                return str;

            if (key.IndexOfAny(new char[] {'=',',' }) > -1)
                throw new Exception("Key里不允许包含逗号以及等号");

            if (!string.IsNullOrEmpty(value))
                value = value.Replace(",", "&#44;");

            if (string.IsNullOrEmpty(str))//str is null
                return key + "=" + value;

            string o_str = str;//保存原来的串，有可能该串不包含key，则需要直接拼接返回

            str = "," + str + ",";//,a=1,b=2,

            int flag = str.IndexOf("," + key + "=");//多加了2个字符，后面会减去
            if (flag > -1)
            {
                string sHead = "", sEnd = "";
                int lenHead;
                lenHead = flag + key.Length + 2;//,key=,---前面有一个逗号，后面有一个=号，所以要加2
                //Response.Write(lenHead + "<br />");

                int o_valueLength = 0, endStartIndex = 0;//原来的值的长度，后面的串开始的index
                endStartIndex = str.IndexOf(',', lenHead);
                o_valueLength = endStartIndex - lenHead;//,a=1
                //Response.Write(o_valueLength + "<br />");

                sHead = str.Substring(1, lenHead - 1);//得到开头的串，原串开头加了一个逗号
                //Response.Write(sHead + "<br />");

                sEnd = str.Substring(endStartIndex, str.Length - endStartIndex - 1);//尾串，长度减去起始位置，再减一，因为尾部增加过一个逗号
                //Response.Write(sEnd + "<br />");

                return sHead + value + sEnd;
            }//if
            else//不存在这个key，则直接拼接
                return o_str + "," + key + "=" + value;
        }*/

        /// <summary>
        /// 快速替换
        /// </summary>
        /// <param name="original"></param>
        /// <param name="pattern"></param>
        /// <param name="replacement"></param>
        /// <returns></returns>
        public static string FastReplace(string original, string pattern, string replacement)
        {
            int count, position0, position1;
            count = position0 = position1 = 0;
            int inc = (original.Length / pattern.Length) * (replacement.Length - pattern.Length);
            char[] chars = new char[original.Length + Math.Max(0, inc)];
            while ((position1 = System.Globalization.CompareInfo.GetCompareInfo("en").IndexOf(original, pattern, position0, System.Globalization.CompareOptions.IgnoreCase)) != -1)
            {
                for (int i = position0; i < position1; ++i) chars[count++] = original[i];
                for (int i = 0; i < replacement.Length; ++i) chars[count++] = replacement[i];
                position0 = position1 + pattern.Length;
            }
            if (position0 == 0) return original;
            for (int i = position0; i < original.Length; ++i) chars[count++] = original[i];
            return new string(chars, 0, count);
        }

        /// <summary>
        /// 进行指定的替换(脏字过滤)
        /// </summary>
        /// <param name="str"></param>
        /// <param name="bantext"></param>
        /// <returns></returns>
        public static string StrFilter(string str, string bantext)
        {
            string text1 = "";
            string text2 = "";
            string[] textArray1 = SplitString(bantext, "\r\n");
            for (int num1 = 0; num1 < textArray1.Length; num1++)
            {
                text1 = textArray1[num1].Substring(0, textArray1[num1].IndexOf("="));
                text2 = textArray1[num1].Substring(textArray1[num1].IndexOf("=") + 1);
                str = str.Replace(text1, text2);
            }
            return str;
        }

        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <param name="strContent"></param>
        /// <param name="strSplit"></param>
        /// <param name="p_3"></param>
        /// <returns></returns>
        public static string[] SplitString(string strContent, string strSplit, int p_3)
        {
            string[] result = new string[p_3];

            string[] splited = SplitString(strContent, strSplit);

            for (int i = 0; i < p_3; i++)
            {
                if (i < splited.Length)
                    result[i] = splited[i];
                else
                    result[i] = string.Empty;
            }

            return result;
        }

        /// <summary>
        /// 返回 HTML 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>编码结果</returns>
        public static string HtmlEncode(string str)
        {
            if (string.IsNullOrEmpty(str))
                return "";

            StringBuilder sb = new StringBuilder(str);
            sb.Replace("&", "&amp;");
            sb.Replace("\"", "&quot;");
            sb.Replace("<", "&lt;");
            sb.Replace(">", "&gt;");
            //sb.Replace(" ", "&nbsp;");

            return sb.ToString();

            //return HttpUtility.HtmlEncode(str);
        }

        /// <summary>
        /// 返回 HTML 字符串的解码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>解码结果</returns>
        public static string HtmlDecode(string str)
        {
            if (string.IsNullOrEmpty(str))
                return "";

            StringBuilder sb = new StringBuilder(str);
            sb.Replace("&gt;", ">");
            sb.Replace("&lt;", "<");
            sb.Replace("&quot;", "\"");
            sb.Replace("&amp;", "&");

            return sb.ToString();
            //return HttpUtility.HtmlDecode(str);
        }

        /// <summary>
        /// 返回 URL 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>编码结果</returns>
        public static string UrlEncode(string str)
        {
            return HttpUtility.UrlEncode(str);
        }

        /// <summary>
        /// 返回 URL 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>解码结果</returns>
        public static string UrlDecode(string str)
        {
            return HttpUtility.UrlDecode(str);
        }

        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <param name="strContent"></param>
        /// <param name="strSplit"></param>
        /// <returns></returns>
        public static string[] SplitString(string strContent, string strSplit)
        {
            if (strContent.IndexOf(strSplit) < 0)
            {
                string[] tmp = { strContent };
                return tmp;
            }
            return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase);
        }

        /// <summary>
        /// 替换sql语句中的引号
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ReplaceQuotationMarks(string str)
        {
            if (str == null)
                return null;
            else
                return str.Replace("'", "''");
        }

        /// <summary>
        /// 替换回车换行符为html换行符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string StrFormat(string str)
        {
            string str2;
            if (str == null)
                str2 = "";
            else
            {
                str = str.Replace("\r\n", "<br />");
                str = str.Replace("\n", "<br />");
                str2 = str;
            }
            return str2;
        }

        /// <summary>
        /// 生成指定数量的指定符号
        /// </summary>
        /// <param name="num"></param>
        /// <param name="sign"></param>
        /// <returns></returns>
        public static string CreateSigns(int num, string sign)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < num; i++)
            {
                sb.Append(sign);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 自定义的替换字符串函数
        /// </summary>
        public static string ReplaceString(string SourceString, string SearchString, string ReplaceString, bool IsCaseInsensetive)
        {
            return Regex.Replace(SourceString, Regex.Escape(SearchString), ReplaceString, IsCaseInsensetive ? RegexOptions.IgnoreCase : RegexOptions.None);
        }

        /// <summary>
        /// 字符串如果操过指定长度则将超出的部分用指定字符串代替
        /// </summary>
        /// <param name="original">要检查的字符串</param>
        /// <param name="length">指定长度</param>
        /// <param name="fill">用于替换的字符串</param>
        /// <returns>截取后的字符串</returns>
        public static string GetSubString(string original, int length, string fill)
        {
            return GetSubString(original, length, fill, StringFillOption.FillTilTheLength);
        }

        /// <summary>
        /// 字符串填充选项
        /// </summary>
        public enum StringFillOption
        { 
            /// <summary>
            /// 在不足时只填充一次
            /// </summary>
            FillOnetime,
            /// <summary>
            /// 在不足时填充很多次直到达到指定的长度
            /// </summary>
            FillTilTheLength,
            /// <summary>
            /// 在不足时不填充
            /// </summary>
            NoFill,
            /// <summary>
            /// 在被截断的情况下只填充一次
            /// </summary>
            FillOneTimeWhenBeCut
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string GetSubString(string str, int length)
        {
            string temp = str;
            int j = 0;
            int k = 0;
            for (int i = 0; i < temp.Length; i++)
            {
                if (Regex.IsMatch(temp.Substring(i, 1), @"[\u4e00-\u9fa5]+"))
                    j += 2;
                else
                    j += 1;
                if (j <= length)
                    k += 1;
                if (j >= length)
                    return temp.Substring(0, k);
            }
            return temp;
        }
        
        /// <summary>
        /// 字符串如果操过指定长度则将超出的部分用指定字符串代替
        /// </summary>
        /// <param name="original">要检查的字符串</param>
        /// <param name="length">指定长度</param>
        /// <param name="fill">用于填充的字符串</param>
        /// <param name="option">字符串填充选项</param>
        /// <returns></returns>
        public static string GetSubString(string original, int length, string fill, StringFillOption option)
        {
            int l = GetStringLength(original);
            if (l == length)//相等,退出
                return original;

            string temp = String.Empty;
            temp = GetSubString(original, length);

            int temp_length = GetStringLength(temp);
            if (temp_length < l)
            {
                switch (option)
                {
                    case StringFillOption.FillOnetime:
                        temp = temp + fill;
                        break;
                    case StringFillOption.NoFill:
                        break;
                    case StringFillOption.FillTilTheLength:
                        temp = temp + CreateSigns(length - temp_length, fill);
                        break;
                }
            }

            return temp;
        }

        /// <summary>
        /// 取左边若干个字符，多余的被截断
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="l">长度</param>
        /// <param name="fetch">在后面弥补的串</param>
        /// <returns></returns>
        public static string GetLeftString(string str, int l, string fetch)
        {
            return GetSubString(str, l, fetch, StringFillOption.FillOnetime);
        }

        /// <summary>
        /// 取左边若干个字符，多余的被截断
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="l">长度</param>
        /// <returns></returns>
        public static string GetLeftString(string str, int l)
        {
            return GetSubString(str, l, "", StringFillOption.NoFill);
        }

        /// <summary>
        /// 截取字符串右边若干字符
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="l">长度</param>
        /// <returns></returns>
        public static string GetRightString(string str, int l)
        {
            //截取右边L个字符
            if (str == System.String.Empty && l > 0)
                return "";
            else
            {
                if (l < str.Length)
                    return str.Substring(str.Length - l, l);
                else
                    return str;
            }
        }

        /// <summary>
        /// 从字符串的指定位置截取指定长度的子字符串
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="startIndex">子字符串的起始位置</param>
        /// <param name="length">子字符串的长度</param>
        /// <returns>子字符串</returns>
        public static string CutString(string str, int startIndex, int length)
        {
            return str.Substring(startIndex, length);
        }

        /// <summary>
        /// 从字符串的指定位置开始截取到字符串结尾的了符串
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="startIndex">子字符串的起始位置</param>
        /// <returns>子字符串</returns>
        public static string CutString(string str, int startIndex)
        {
            return CutString(str, startIndex, str.Length);
        }

        /// <summary>
        /// 2010-09-13增加 Trim(new char[] { ' ', '\n', '\r' })
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Trim(string str)
        {
            if (!string.IsNullOrEmpty(str))
                return str.Trim(new char[] { ' ', '\n', '\r' });

            return null;
        }

        /*/// <summary>
        /// 删除字符串尾部的回车/换行/空格
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string RTrim(string str)
        {
            for (int i = str.Length; i >= 0; i--)
            {
                if (str[i].Equals(" ") || str[i].Equals("\r") || str[i].Equals("\n"))
                    str.Remove(i, 1);
            }
            return str;
        }*/

        /// <summary>
        /// 清除给定字符串中的回车及换行符
        /// </summary>
        /// <param name="str">要清除的字符串</param>
        /// <returns>清除后返回的字符串</returns>
        public static string ClearBR(string str)
        {
            //Regex r = null;
            Match m = null;

            //r = new Regex(@"(\r\n)",RegexOptions.IgnoreCase);
            for (m = regexBr.Match(str); m.Success; m = m.NextMatch())
            {
                str = str.Replace(m.Groups[0].ToString(), "");
            }
            return str;
        }

        /// <summary>
        /// 返回字符串真实长度, 1个汉字长度为2
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int GetStringLength(string str)
        {
            return Encoding.UTF8.GetBytes(str).Length;
        }

        /// <summary>
        /// 移除Html标记
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RemoveHtml(string content)
        {
            if (string.IsNullOrEmpty(content)) return string.Empty;
            string regexstr = @"<[^>]*>";
            return Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
        }

        /// <summary>
        /// 过滤HTML中的不安全标签
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RemoveUnsafeHtml(string content)
        {
            if (string.IsNullOrEmpty(content)) return string.Empty;
            content = Regex.Replace(content, @"(\<|\s+)o([a-z]+\s?=)", "$1$2", RegexOptions.IgnoreCase);
            content = Regex.Replace(content, @"(script|frame|form|meta|behavior|style)([\s|:|>])+", "$1.$2", RegexOptions.IgnoreCase);
            return content;
        }

        /// <summary>
        /// 从HTML中获取文本,保留br,p,img
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string GetTextFromHTML(string content)
        {
            if (string.IsNullOrEmpty(content)) return string.Empty;
            System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(@"</?(?!br|/?p|img)[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            return regEx.Replace(content, "");
        }

        /// <summary>
        /// 去掉string里的可能包含的SQL保留字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Nosql(string str)
        {
            //过滤非法字符
            if (string.IsNullOrEmpty(str))
                return "";
            else
            {
                StringBuilder sb = new StringBuilder(str);
                //sb.Replace(";", "&#59;");
                sb.Replace("'", "&#39;");
                //sb.Replace("\"", "&quot;");
                //sb.Replace("chr(9)", "&nbsp;");
                //sb.Replace("chr(10)", "<br />");
                //sb.Replace("chr(13)", "<br />");
                //sb.Replace("chr(32)", "&nbsp;");
                //sb.Replace("chr(34)", "&quot;");
                //sb.Replace("chr(39)", "&#39;");
                //sb.Replace("script", "&#115cript");
                sb.Replace("<", "&lt;");
                sb.Replace(">", "&gt;");
                //str = str.Replace("(", "&#40;");
                //str = str.Replace(")", "&#41;");
                //sb.Replace("--", "&#45;&#45;");
                return sb.ToString();
            }
        }

        /// <summary>
        /// 去掉最后一或者几个符号，截取最后一次出现的该串的前面的部分
        /// </summary>
        /// <param name="origin"></param>
        /// <param name="sign">符号，可以为多个字符</param>
        /// <returns></returns>
        public static string RemoveLastChars(string origin,string sign)
        {
            if (origin.IndexOf(sign) == -1)
                return origin;
            return origin.Substring(0, origin.LastIndexOf(sign));
        }

        /// <summary>
        /// 生成随机的字符
        /// </summary>
        /// <param name="len">生成字符的个数</param>
        /// <returns>string</returns>
        public static string GetRndChars(int len)
        {
            //string s = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            return GetRndChars(len, null);
        }

        /// <summary>
        /// 生成随机的字符
        /// </summary>
        /// <param name="len">生成字符的个数</param>
        /// <param name="source">字典，字符的范围，用逗号分割开</param>
        /// <returns></returns>
        public static string GetRndChars(int len, string source)
        {
            //string[] arr = source.Split(',');
            //string[] arr = source.Split(',');

            if (string.IsNullOrEmpty(source))
                source = DEFAULT_CHARS;

            StringBuilder sb = new StringBuilder();

            //采用一个简单的算法以保证生成随机数的不同
            int c = source.Length;
            for (int i = 1; i < len + 1; i++)
            {
                sb.Append(source[rand.Next(0, c - 1)]);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 得到汉字的首字母
        /// </summary>
        /// <param name="strText"></param>
        /// <returns></returns>
        public static string GetChineseSpell(string strText)
        {
            int len = strText.Length;
            //string myStr = "";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < len; i++)
            {
                //myStr += getSpell(strText.Substring(i, 1)).ToLower();
                sb.Append(GetFirstSpell(strText.Substring(i, 1)).ToLower());
            }
            return sb.ToString();
        }
		
		/// <summary>
        /// 返回字符串各字首字母
        /// </summary>
        /// <param name="str">输入</param>
        /// <returns>输出字母</returns>
        public static string GetLetterFromString(string str)
        {
            string tempStr = "";
            if (!string.IsNullOrEmpty(str))
            {
                foreach (char c in str)
                {
                    if (((int)c >= 33) && ((int)c <= 126))
                    {
                        //字母和符号原样保留 
                        tempStr += c.ToString();
                    }
                    else
                    {
                        //累加拼音声母
                        tempStr += GetFirstSpell(c.ToString());
                    }
                }
            }
            return tempStr;
        }

        /// <summary>
        /// 得到汉字的首字母
        /// </summary>
        /// <param name="cnChar"></param>
        /// <returns></returns>
        public static string GetFirstSpell(string cnChar)
        {
            //byte[] arrCN = Encoding.Default.GetBytes(cnChar);//GetEncoding("gb2312")
            //if (arrCN.Length > 1)
            //{
            //    int area = (short)arrCN[0];
            //    int pos = (short)arrCN[1];
            //    int code = (area << 8) + pos;
            //    int[] areacode = { 45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614, 48119, 48119, 49062, 49324, 49896, 50371, 50614, 50622, 50906, 51387, 51446, 52218, 52698, 52698, 52698, 52980, 53689, 54481 };
            //    for (int i = 0; i < 26; i++)
            //    {
            //        int max = 55290;
            //        if (i != 25) max = areacode[i + 1];
            //        if (areacode[i] <= code && code < max)
            //        {
            //            return Encoding.Default.GetString(new byte[] { (byte)(65 + i) });
            //        }
            //    }
            //    return " ";
            //}
            //else
            //    return cnChar;
            string str = cnChar;
            if (str.CompareTo("吖") < 0) return str;
            if (str.CompareTo("八") < 0) return "A";
            if (str.CompareTo("嚓") < 0) return "B";
            if (str.CompareTo("咑") < 0) return "C";
            if (str.CompareTo("妸") < 0) return "D";
            if (str.CompareTo("发") < 0) return "E";
            if (str.CompareTo("旮") < 0) return "F";
            if (str.CompareTo("铪") < 0) return "G";
            if (str.CompareTo("讥") < 0) return "H";
            if (str.CompareTo("咔") < 0) return "J";
            if (str.CompareTo("垃") < 0) return "K";
            if (str.CompareTo("嘸") < 0) return "L";
            if (str.CompareTo("拏") < 0) return "M";
            if (str.CompareTo("噢") < 0) return "N";
            if (str.CompareTo("妑") < 0) return "O";
            if (str.CompareTo("七") < 0) return "P";
            if (str.CompareTo("亽") < 0) return "Q";
            if (str.CompareTo("仨") < 0) return "R";
            if (str.CompareTo("他") < 0) return "S";
            if (str.CompareTo("哇") < 0) return "T";
            if (str.CompareTo("夕") < 0) return "W";
            if (str.CompareTo("丫") < 0) return "X";
            if (str.CompareTo("帀") < 0) return "Y";
            if (str.CompareTo("咗") < 0) return "Z";
            return str;
        }
    }
}
